package service.impl;

import com.github.pagehelper.PageHelper;
import mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import pojo.User;
import service.IUserService;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 用户业务实现类
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(String code, String mail, String password) {
        //根据用户邮箱进行查询
        User user = userMapper.selectByMail(mail);
        //结果为空，登录失败
        if(user==null){
            return null;
        }
        //获取密码
        String userPassword = user.getUserPassword();
        try {
            //密码验证
            String md5DigestAsHex = DigestUtils.md5DigestAsHex((userPassword+code).getBytes("utf-8"));
            //验证失败，登录失败
            if(!md5DigestAsHex.equals(password)){
                return null;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //验证成功,返回用户信息
        return user;
    }

    @Override
    public User getUserById(int id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public int modifyById(User user) {
        int result = userMapper.updateByPrimaryKey(user);
        return result;
    }

    @Override
    public int modifyInformationById(User user) {
        int result = userMapper.updateByPrimaryKeyForInformation(user);
        return result;
    }

    @Override
    public int modifyHeadImgById(User user) {
        int i = userMapper.updateByPrimaryKeyForHeadImg(user);
        return i;
    }

    @Override
    public int modifyPasswordById(User user) {
        int i = userMapper.updateByPrimaryKeySelective(user);
        return i;
    }

    @Override
    public User getUserByMail(String mail) {
        User user = userMapper.selectByMail(mail);;
        return user;
    }

    @Override
    public int addUser(User user) {
        int insert = userMapper.insert(user);
        return insert;
    }

    @Override
    public List<User> getReplyTop(int limit) {
        PageHelper.startPage(1,limit );
        List<User> users = userMapper.selectReplyTop();
        return users;
    }

    @Override
    public User getUserByName(String userName) {
        User user = userMapper.selectByName(userName);
        return user;
    }
}
